package com.qd.thirdpart.controller;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.crypto.SecureUtil;
import com.cdqidi.annotation.IgnoreLogPrint;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.thirdpart.domain.ThirdJtParkSyncDTO;
import com.qd.thirdpart.service.ThirdPartSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author sjk
 */
@Controller
@RequestMapping("/sys/thirdPart")
@Slf4j
@RequiredArgsConstructor
@IgnoreLogPrint(bodyLogPrint = false)
public class ThirdPartController {
    private final ObjectMapper objectMapper;
    private final ValidatorUtil validatorUtil;

    private final ThirdPartSyncService thirdPartSyncService;
    private final HttpServletResponse response;

    private static final String SECURITY_KEY = "CDJT-%6SDS*";

    /**
     * 同步交投停车场数据
     *
     * @param param 停车场数据
     */
    @RequestMapping("/carParkSync")
    @ResponseBody
    public void carPark(@RequestBody String param) {
        try {
            param = UnicodeUtil.toString(param);
//            log.info("解码JSON： " + param);
            JsonNode jsonNode = objectMapper.readTree(param);
            String checksum = jsonNode.get("checksum").asText();
            String listStr = jsonNode.get("list").toString();
            String s = SecureUtil.md5(listStr + SECURITY_KEY);
            if (!s.equals(checksum)) {
                throw new ApiException("签名失败,客户端checksum：" + checksum + ",服务端checksum: " + s);
            }
            List<ThirdJtParkSyncDTO> list = objectMapper.readValue(listStr, new TypeReference<>() {
            });
            list.forEach(thirdJtParkSyncDTO -> {
                if (log.isDebugEnabled()) {
                    if (null == thirdJtParkSyncDTO.getParkNo() || null == thirdJtParkSyncDTO.getFeeRuleId()) {
                        log.debug(thirdJtParkSyncDTO.toString());
                    }
                }
                validatorUtil.checkValid(thirdJtParkSyncDTO, DefaultGroup.class);
            });
            thirdPartSyncService.save(list);
            renderText("{\"result\": \"success\"}");
        } catch (Exception e) {
            log.error("同步交投停车场数据", e);
            renderText("{\"result\": \"failure\"}");
        }

    }

    protected void renderText(String text) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain;charset:utf-8;");
        try (PrintWriter out = response.getWriter()) {
            out.append(text);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
